﻿using System;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows.Forms;
using Kay.WebClientApplication.Models.Entitys;
using Newtonsoft.Json;

namespace Kay.WebClientApplication
{
    /// <summary>
    /// 启动窗体
    /// </summary>
    public partial class Startup : Form
    {
        /// <summary>
        /// 当前使用的 Cookie 容器
        /// </summary>
        public CookieContainer Cookie { get; set; }

        /// <summary>
        /// Web 客户端对象
        /// </summary>
        public WebClientExpert WebClient { get; set; }

        /// <summary>
        /// 编码
        /// </summary>
        public Encoding Encoding { get; set; }

        /// <summary>
        /// 数据文件名称
        /// </summary>
        public readonly string DataFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DataDirectory",
            "DataSetWebClient.dat");

        public Datas dataSetWebClient { get; set; }

        /// <summary>
        /// 初始化启动窗体
        /// </summary>
        public Startup()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Web 客户端创建器
        /// </summary>
        /// <returns>Web 客户端</returns>
        public WebClientExpert Creator()
        {
            if (WebClient != null) return WebClient;
            WebClientExpert web;
            if (Cookie == null)
            {
                web = new WebClientExpert();
                Cookie = web.Cookie;
            }
            else
            {
                web = new WebClientExpert(Cookie);
            }
            web.Encoding = Encoding;
            return web;
        }

        // 加载窗体
        private void Startup_Load(object sender, System.EventArgs e)
        {
            if (File.Exists(DataFileName))
            {
                var data = File.ReadAllText(DataFileName);
                dataSetWebClient = JsonConvert.DeserializeObject<Datas>(data);
            }
            if (dataSetWebClient == null)
            {
                dataSetWebClient = new Datas();
            }
            if (dataSetWebClient.UriHistories == null)
            {
                dataSetWebClient.UriHistories = new BindingList<UriHistory>();
            }
            if (dataSetWebClient.Querys == null)
            {
                dataSetWebClient.Querys = new BindingList<NameValue>();
            }
            if (dataSetWebClient.Handers == null)
            {
                dataSetWebClient.Handers = new BindingList<NameValue>();
            }
            if (dataSetWebClient.Bodys == null)
            {
                dataSetWebClient.Bodys = new BindingList<NameValue>();
            }
            comboBoxMethod.SelectedIndex = 0;
            RefreshData();
        }

        /// <summary>
        /// 刷新数据显示
        /// </summary>
        public void RefreshData()
        {
            comboBoxUri.DataSource = dataSetWebClient.UriHistories;
            dataGridViewQuery.DataSource = dataSetWebClient.Querys;
            dataGridViewHander.DataSource = dataSetWebClient.Handers;
            dataGridViewBody.DataSource = dataSetWebClient.Bodys;
        }

        // 关闭窗体
        private void Startup_FormClosing(object sender, FormClosingEventArgs e)
        {
            var dir = Path.GetDirectoryName(DataFileName);
            if (!Directory.Exists(dir))
                if (dir != null) Directory.CreateDirectory(dir);
            var data = JsonConvert.SerializeObject(dataSetWebClient);
            File.WriteAllText(DataFileName, data);
        }

        // 发送请求
        private void buttonSend_Click(object sender, EventArgs e)
        {
            if (!SetUriHistory())
                return;
        }

        private bool SetUriHistory()
        {
            // 处理数据合法性
            errorProvider1.Clear();
            if (string.IsNullOrWhiteSpace(comboBoxUri.Text))
            {
                errorProvider1.SetIconAlignment(comboBoxUri, ErrorIconAlignment.MiddleLeft);
                errorProvider1.SetError(comboBoxUri, "请填写 Url 地址！");
                return false;
            }
            if (comboBoxMethod.SelectedIndex < 0)
            {
                errorProvider1.SetIconAlignment(comboBoxMethod, ErrorIconAlignment.MiddleLeft);
                errorProvider1.SetError(comboBoxMethod, "请选择请求方式！");
                return false;
            }

            // 加入记录
            var url = comboBoxUri.Text;
            var row = dataSetWebClient.UriHistories.FirstOrDefault(r => r.Url == url);
            if (row == null)
            {
                var uriRow = dataSetWebClient.UriHistories.AddNew();
                comboBoxUri.SelectedIndex = dataSetWebClient.UriHistories.Count - 1;
                if (uriRow != null)
                {
                    uriRow.Url = url;
                    //uriRow.Method = comboBoxMethod.SelectedIndex;
                    uriRow.CreationTime = DateTime.Now;
                }

                if (dataSetWebClient.UriHistories.Count > 20)
                {
                    var item = dataSetWebClient.UriHistories.First(
                        r => r.CreationTime == dataSetWebClient.UriHistories.Min(j => j.CreationTime));
                    var querys = dataSetWebClient.Querys.Where(r => r.Url == item.Url);
                    foreach (var nameValuese in querys)
                    {
                        dataSetWebClient.Querys.Remove(nameValuese);
                    }
                    var handers = dataSetWebClient.Handers.Where(r => r.Url == item.Url);
                    foreach (var nameValuese in handers)
                    {
                        dataSetWebClient.Handers.Remove(nameValuese);
                    }
                    var bodys = dataSetWebClient.Bodys.Where(r => r.Url == item.Url);
                    foreach (var nameValuese in bodys)
                    {
                        dataSetWebClient.Bodys.Remove(nameValuese);
                    }
                    dataSetWebClient.UriHistories.Remove(item);
                }
                dataSetWebClient.UriHistories.ResetItem(dataSetWebClient.UriHistories.IndexOf(uriRow));
            }
            else
            {
                row.CreationTime = DateTime.Now;
                //row.Method = comboBoxMethod.SelectedIndex;
                dataSetWebClient.UriHistories.ResetItem(dataSetWebClient.UriHistories.IndexOf(row));
            }
            return true;
        }

        // 设置请求参数（Query）
        private void buttonSetQuery_Click(object sender, EventArgs e)
        {
            if (!SetUriHistory())
                return;

            // 处理数据合法性
            errorProvider1.Clear();
            if (string.IsNullOrWhiteSpace(textBoxQueryName.Text))
            {
                errorProvider1.SetIconAlignment(textBoxQueryName, ErrorIconAlignment.MiddleLeft);
                errorProvider1.SetError(textBoxQueryName, "请填写参数名称！");
                return;
            }
            if (string.IsNullOrWhiteSpace(textBoxQueryValue.Text))
            {
                errorProvider1.SetIconAlignment(textBoxQueryValue, ErrorIconAlignment.MiddleLeft);
                errorProvider1.SetError(textBoxQueryValue, "请填写参数值！");
                return;
            }

            // 加入记录
            var name = textBoxQueryName.Text;
            var row = dataSetWebClient.Querys.FirstOrDefault(r => r.Name == name);
            if (row == null)
            {
                var query = dataSetWebClient.Querys.AddNew();
                if (query != null)
                {
                    query.Name = name;
                    query.Url = comboBoxUri.Text;
                    query.Value = textBoxQueryValue.Text;
                    query.CreationTime = DateTime.Now;
                }
                dataSetWebClient.Querys.ResetItem(dataSetWebClient.Querys.IndexOf(query));
                dataGridViewQuery.Rows[dataSetWebClient.Querys.IndexOf(query)].Selected = true;
                dataGridViewQuery.CurrentCell = dataGridViewQuery.Rows[dataSetWebClient.Querys.IndexOf(query)].Cells[0];
                dataGridViewQuery.FirstDisplayedScrollingRowIndex = dataSetWebClient.Querys.IndexOf(query);
            }
            else
            {
                row.CreationTime = DateTime.Now;
                row.Value = textBoxQueryValue.Text;
                dataSetWebClient.Querys.ResetItem(dataSetWebClient.Querys.IndexOf(row));
                dataGridViewQuery.Rows[dataSetWebClient.Querys.IndexOf(row)].Selected = true;
                dataGridViewQuery.CurrentCell = dataGridViewQuery.Rows[dataSetWebClient.Querys.IndexOf(row)].Cells[0];
                dataGridViewQuery.FirstDisplayedScrollingRowIndex = dataSetWebClient.Querys.IndexOf(row);
            }

            textBoxQueryName.Clear();
            textBoxQueryValue.Clear();
        }

        // 设置请求头（Hander）
        private void buttonSetHander_Click(object sender, EventArgs e)
        {
            if (!SetUriHistory())
                return;

            // 处理数据合法性
            errorProvider1.Clear();
            if (string.IsNullOrWhiteSpace(textBoxHanderName.Text))
            {
                errorProvider1.SetIconAlignment(textBoxHanderName, ErrorIconAlignment.MiddleLeft);
                errorProvider1.SetError(textBoxHanderName, "请填写参数名称！");
                return;
            }
            if (string.IsNullOrWhiteSpace(textBoxHanderValue.Text))
            {
                errorProvider1.SetIconAlignment(textBoxHanderValue, ErrorIconAlignment.MiddleLeft);
                errorProvider1.SetError(textBoxHanderValue, "请填写参数值！");
                return;
            }

            // 加入记录
            var name = textBoxHanderName.Text;
            var row = dataSetWebClient.Handers.FirstOrDefault(r => r.Name == name);
            if (row == null)
            {
                var hander = dataSetWebClient.Handers.AddNew();
                if (hander != null)
                {
                    hander.Name = name;
                    hander.Url = comboBoxUri.Text;
                    hander.Value = textBoxHanderValue.Text;
                    hander.CreationTime = DateTime.Now;
                }
                dataSetWebClient.Handers.ResetItem(dataSetWebClient.Handers.IndexOf(hander));
                dataGridViewHander.Rows[dataSetWebClient.Handers.IndexOf(hander)].Selected = true;
                dataGridViewHander.CurrentCell = dataGridViewHander.Rows[dataSetWebClient.Handers.IndexOf(hander)].Cells[0];
                dataGridViewHander.FirstDisplayedScrollingRowIndex = dataSetWebClient.Handers.IndexOf(hander);
            }
            else
            {
                row.CreationTime = DateTime.Now;
                row.Value = textBoxHanderValue.Text;
                dataSetWebClient.Handers.ResetItem(dataSetWebClient.Handers.IndexOf(row));
                dataGridViewHander.Rows[dataSetWebClient.Handers.IndexOf(row)].Selected = true;
                dataGridViewHander.CurrentCell = dataGridViewHander.Rows[dataSetWebClient.Handers.IndexOf(row)].Cells[0];
                dataGridViewHander.FirstDisplayedScrollingRowIndex = dataSetWebClient.Handers.IndexOf(row);
            }

            textBoxHanderName.Clear();
            textBoxHanderValue.Clear();
        }

        // 设置请求体（Body）
        private void buttonSetBody_Click(object sender, EventArgs e)
        {
            if (!SetUriHistory())
                return;

            // 处理数据合法性
            errorProvider1.Clear();
            if (string.IsNullOrWhiteSpace(textBoxBodyName.Text))
            {
                errorProvider1.SetIconAlignment(textBoxBodyName, ErrorIconAlignment.MiddleLeft);
                errorProvider1.SetError(textBoxBodyName, "请填写参数名称！");
                return;
            }
            if (string.IsNullOrWhiteSpace(textBoxBodyValue.Text))
            {
                errorProvider1.SetIconAlignment(textBoxBodyValue, ErrorIconAlignment.MiddleLeft);
                errorProvider1.SetError(textBoxBodyValue, "请填写参数值！");
                return;
            }

            // 加入记录
            var name = textBoxBodyName.Text;
            var row = dataSetWebClient.Bodys.FirstOrDefault(r => r.Name == name);
            if (row == null)
            {
                var body = dataSetWebClient.Bodys.AddNew();
                if (body != null)
                {
                    body.Name = name;
                    body.Url = comboBoxUri.Text;
                    body.Value = textBoxBodyValue.Text;
                    body.CreationTime = DateTime.Now;
                }
                dataSetWebClient.Bodys.ResetItem(dataSetWebClient.Bodys.IndexOf(body));
                dataGridViewBody.Rows[dataSetWebClient.Bodys.IndexOf(body)].Selected = true;
                dataGridViewBody.CurrentCell = dataGridViewBody.Rows[dataSetWebClient.Bodys.IndexOf(body)].Cells[0];
                dataGridViewBody.FirstDisplayedScrollingRowIndex = dataSetWebClient.Bodys.IndexOf(body);
            }
            else
            {
                row.CreationTime = DateTime.Now;
                row.Value = textBoxBodyValue.Text;
                dataSetWebClient.Bodys.ResetItem(dataSetWebClient.Bodys.IndexOf(row));
                dataGridViewBody.Rows[dataSetWebClient.Bodys.IndexOf(row)].Selected = true;
                dataGridViewBody.CurrentCell = dataGridViewBody.Rows[dataSetWebClient.Bodys.IndexOf(row)].Cells[0];
                dataGridViewBody.FirstDisplayedScrollingRowIndex = dataSetWebClient.Bodys.IndexOf(row);
            }

            textBoxBodyName.Clear();
            textBoxBodyValue.Clear();
        }

        private void dataGridViewQuery_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            var dataGrid = (DataGridView)sender;
            try
            {
                for (int i = 0; i < dataGrid.Rows.Count; i++)
                {
                    var r = dataGrid.Rows[i];
                    r.HeaderCell.Value = $"{i + 1}";
                }
            }
            catch (ArgumentOutOfRangeException) { }
            dataGrid.Refresh();
        }

        private void checkBoxShowPwd_CheckedChanged(object sender, EventArgs e)
        {
            textBoxPwd.PasswordChar = checkBoxShowPwd.Checked ? char.MinValue : '*';
        }

        private void comboBoxUri_TextUpdate(object sender, EventArgs e)
        {

        }
    }
}
